<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2022/9/4
 * Time: 13:00
 */

namespace App\Tools;


use Ixudra\Curl\Facades\Curl;
use Ramsey\Uuid\Uuid;

class Translator
{

    private $key;
    private $region;

    private $youdaoAppKey;
    private $youdaoSecKey;

    public function __construct(){
        $this->key = config("translator.azure.key");
        $this->region = config("translator.azure.region");
        $this->youdaoAppKey = config("translator.youdao.appkey");
        $this->youdaoSecKey = config("translator.youdao.seckey");
    }

    public function azure($text, $to='en') {
		if('en' == $to && $this->isAllEnglish($text)) {
			return $text;
		}
        $response = Curl::to('https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=' . $to)
            ->withHeaders([
                'Ocp-Apim-Subscription-Key' => $this->key,
                'Ocp-Apim-Subscription-Region' => $this->region,
        ])
            ->withData([[
            'Text'=>$text
            ]])
            ->asJson(true)
            ->post();
        //print_r($response);
        if ($response[0]['translations'][0]['text'] ?? false) {
            return $response[0]['translations'][0]['text'];
        }
        return $text;
    }


    public function youdao($text, $to='en')
    {
        $salt = Uuid::uuid4()->toString();
        $args = array(
            'q' => $text,
            'appKey' => $this->youdaoAppKey,
            'salt' => $salt,
        );
        $args['from'] = 'auto';
        $args['to'] = $to;
        $args['signType'] = 'v3';
        $curtime = strtotime("now");
        $args['curtime'] = $curtime;
        $signStr = $this->youdaoAppKey . $this->truncate($text) . $salt . $curtime . $this->youdaoSecKey;
        $args['sign'] = hash("sha256", $signStr);
        //$args['vocabId'] = '您的用户词表ID';
        //$ret = call('https://openapi.youdao.com/api', $args);
        $response = Curl::to('https://openapi.youdao.com/api')->withData($args)->asJsonResponse(true)->post();
        if ($response['translation'][0] ?? false) {
            return $response['translation'][0];
        }
        return '';
    }


    private function truncate($q) {
        $len = $this->abslength($q);
        return $len <= 20 ? $q : (mb_substr($q, 0, 10) . $len . mb_substr($q, $len - 10, $len));
    }

    private function abslength($str)
    {
        if(empty($str)){
            return 0;
        }
        if(function_exists('mb_strlen')){
            return mb_strlen($str,'utf-8');
        }
        else {
            preg_match_all("/./u", $str, $ar);
            return count($ar[0]);
        }
    }

	/**
	 * 判断是否为全英文
	 * @param string $sStr
	 * @return boolean
	 */
	function isAllEnglish($sStr) {
		return strlen($sStr) === strlen(mb_convert_encoding($sStr, 'ISO-8859-1'));
	}
}